package com.sogoodsoft.service.project;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sogoodsoft.dao.common.CommonHibernateDao;
import com.sogoodsoft.dao.project.AssessmentDao;
import com.sogoodsoft.dao.project.PrjFileDao;
import com.sogoodsoft.dao.project.ProjectDao;
import com.sogoodsoft.entity.app.Organization;
import com.sogoodsoft.entity.project.Assessment;
import com.sogoodsoft.entity.project.PrjFile;
import com.sogoodsoft.entity.project.Project;
import com.sogoodsoft.service.common.AbstractService;

@Component
@Transactional
public class ProjectService extends AbstractService<Project,Long> {

	private ProjectDao dao;
	private PrjFileDao prjFileDao;
	private AssessmentDao assessmentDao;



	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public CommonHibernateDao getDao() {
		return dao;
	}

	@Autowired
	public void setDao(ProjectDao dao) {
		this.dao = dao;
	}

	public PrjFileDao getPrjFileDao() {
		return prjFileDao;
	}

	/**级联删除项目及审核记录
	 * @param project
	 
	public void delete(Project project){
		List<Assessment> list = project.getAssessments();
		for(Assessment a:list){
			assessmentDao.delete(a);
		}
		dao.delete(project);
	}
*/
	@Autowired
	public void setPrjFileDao(PrjFileDao prjFileDao) {
		this.prjFileDao = prjFileDao;
	}

	public void save(Project prj, PrjFile... files) {
		// 保存项目
		prj.setTotal(needCount(prj));
		dao.save(prj);

		// 保存项目文件
		if(files!=null){
			for (PrjFile file : files) {
				file.setProject(prj);
				prjFileDao.save(file);
			}
		}
		
		//向第一个申核单位添加申核请求
		Assessment assessment = new Assessment();		
		//需申核的单位 当前单位第一个申核
		assessment.setOrganization(prj.getOrganization());		
		//申核项目
		assessment.setProject(prj);		
		assessmentDao.save(assessment);	

	}
	
	
	/**
	 * 计算需要申核的数量
	 * 当前申报单位，需在本单位先申核
	 * @param prj
	 * @return
	 */
	public Long needCount(Project prj){
		int all = 1;
		
		//最终级别
		String target = prj.getSysClass().getValue().trim();
		
		//起始级别
		Organization org = prj.getOrganization();
		String src = org.getType().trim();
		
		while(!src.equals(target)){			
			org = org.getParent();
			if("-1".equals(org.getType()))org = org.getParent();
			all++;
			src = org.getType().trim();			
		}
		
		return new Long(all);
	}

	public AssessmentDao getAssessmentDao() {
		return assessmentDao;
	}

	@Autowired
	public void setAssessmentDao(AssessmentDao assessmentDao) {
		this.assessmentDao = assessmentDao;
	}

}
